import {Injectable} from "@angular/core";
import {Headers, Http} from "@angular/http";
import "rxjs/add/operator/toPromise";

@Injectable()
export class HttpService {

    private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});

    private apiBaseUrl: string = 'http://localhost:8080/';


    constructor(private http: Http) {
    }

    /**
     * 统一发送请求
     * @param params
     * @returns {Promise<{success: boolean, msg: string}>|Promise<R>}
     */
    public request(params: any): any {
        let requestJson = 'requestJson={}';
        let data = params['data'];
        if (data) {
            requestJson = 'requestJson=' + JSON.stringify(data);
        }
        if (params['method'] == 'post' || params['method'] == 'POST') {
            return this.post(this.apiBaseUrl + params['url'], requestJson,params['handleSuccess']);
        }
        else {
            return this.get(this.apiBaseUrl + params['url'], requestJson);
        }
    }

    /**
     * get请求
     * @param url 接口地址
     * @param params 参数
     * @returns {Promise<R>|Promise<U>}
     */
    public get(url: string, params: string): any {
        return this.http.get(url, {search: params})
            .toPromise()
            .then(res => this.handleSuccess(res))
            .catch(res => this.handleError(res));
    }

    /**
     * post请求
     * @param url 接口地址
     * @param params 参数
     * @returns {Promise<R>|Promise<U>}
     */
    public post(url: string, params: string, callback): any {

        return this.http.post(url, params, {headers: this.headers})
            .toPromise()
            .then(res => callback? callback(res):this.handleSuccess(res))
            .catch(res => this.handleError(res));
    }

    /**
     * 处理请求成功
     * @param res
     * @returns {{data: (string|null|((node:any)=>any)
   */
    private handleSuccess(res) {
        return res.json();
    }

    /**
     * 处理请求错误
     * @param error
     * @returns {void|Promise<string>|Promise<T>|any}
     */
    private handleError(error) {
        let msg = '请求失败';
        if (error.status == 400) {
            console.log('请求参数正确');
        }
        if (error.status == 404) {
            console.error('请检查路径是否正确');
        }
        if (error.status == 500) {
            console.error('请求的服务器错误');
        }
        console.log(error);
        return {success: false, message: msg, errorCode: error.status};
    }

}
